import { createApp } from 'vue'
import { addClass, removeClass } from '@/assets/js/dom'

function createLoadingLikeDirective(Component) {
  const relativeClass = 'relativeClass'
  const loadingDirective = {
    mounted(el, binding) {
      const app = createApp(Component)
      const instance = app.mount(document.createElement('div'))
      const name = Component.name
      if (!el[name]) {
        el[name] = {}
      }
      el[name].instance = instance
      // el.instance = instance

      if (binding.value) {
        append(el)
      }
    },

    updated(el, binding) {
      if (binding.value !== binding.oldValue) {
        binding.value ? append(el) : remove(el)
      }
    }
  }

  function append(el) {
    const style = getComputedStyle(el)
    if (['relative', 'absolute', 'fixed'].indexOf(style.position) === -1) {
      addClass(el, relativeClass)
    }
    el.appendChild(el[Component.name].instance.$el)
  }

  function remove(el) {
    removeClass(el, relativeClass)
    el.removeChild(el[Component.name].instance.$el)
  }

  return loadingDirective
}

export default createLoadingLikeDirective
